<?php

namespace app\common\service;

use app\common\model\Recommend as RecommendModel;
use app\common\util\CacheKey;
use app\wxapp\service\WechatUserService as WxappWechatUserService;
use think\facade\Cache;
use think\facade\Db;

class VideoAndTopicService
{

    /**
     * @param array $options
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function select($options = [])
    {
        // 缓存
        ksort($options);
        $cacheKey = CacheKey::WXAPP . '#' . json_encode($options);
        if ($result = Cache::get($cacheKey)) {
            return $result;
        }
        // 分页
        $page = max(1, $options['page'] ?? 1);
        $size = max(1, min(100, $options['size'] ?? 10));
        // 排序，允许参与排序的字段：src_id,hot
        if (!empty($options['order']) && in_array($options['order'], ['src_id', 'hot'])) {
            $order = "ORDER BY `{$options['order']}` DESC";
        }
        // 查询条件
        $where = [];
        // 关键字查询
        if (!empty($options['keyword'])) {
            $where[] = "`title` LIKE '%{$options['keyword']}%'";
        }
        // 分类查询
        if (!empty($options['category'])) {
            $where[] = "`category_id` = {$options['category']}";
        }
        $where = $where ? ('WHERE ' . implode(' AND ', $where)) : '';
        // 查询语句模板
        $sql = 'SELECT * FROM
        (SELECT `id` AS `src_id`, `hot`, `category_id`, 1 AS `type` FROM `video_list` %s UNION
         SELECT `id` AS `src_id`, `hot`, `category_id`, 2 AS `type` FROM `topic` %s ) AS `t`
         %s LIMIT %d,%d';
        // 查询
        $result = Db::query(sprintf($sql, $where, $where, $order ?? '', ($page - 1) * $size, $size));
        // 遍历查询结果，获取完整数据
        foreach ($result as &$item) {
            if (RecommendModel::TYPE_VIDEO == $item['type']) {
                $item['data'] = Db::table('video_list')->field('id,title,out_video_id,cover_url,duration,hot,is_fee,fee')->find($item['src_id']) ?: [];
            } else {
                $item['data'] = Db::table("topic")->field('id,title,cover_url,hot,video_count,fee')->find($item['src_id']) ?: [];
            }
        }
        Cache::set($cacheKey, $result);
        return $result;
    }


    public function recent($page = 1, $pageSize = 10)
    {
        $start = ($page - 1) * $pageSize;
        $result = Db::query("SELECT * FROM (SELECT id as src_id ,hot,category_id,create_time ,1 AS `type` FROM video_list UNION SELECT id as src_id, hot,category_id,create_time ,2 AS `type` FROM topic) AS t order by create_time desc limit " . $start . "," . $pageSize);

        $videoIds = [];
        $topicIds = [];
        foreach ($result as $key => $val) {
            if ($val['type'] == RecommendModel::TYPE_VIDEO) {
                array_push($videoIds, $val['src_id']);
            } else if ($val['type'] == RecommendModel::TYPE_TOPIC) {
                array_push($topicIds, $val['src_id']);
            }
        }

        $videos = Db::table("video_list")->whereIn("id", $videoIds)->column("id,title,out_video_id,cover_url,duration,hot", "id");
        $topics = Db::table("topic")->whereIn("id", $topicIds)->column("id,title,cover_url,hot", "id");


        foreach ($result as $key => $val) {
            if ($val['type'] == RecommendModel::TYPE_VIDEO) {
                $result[$key]['data'] = isset($videos[$val['src_id']]) ? $videos[$val['src_id']] : [];
            } else if ($val['type'] == RecommendModel::TYPE_TOPIC) {
                $result[$key]['data'] = isset($topics[$val['src_id']]) ? $topics[$val['src_id']] : [];
            }
        }

        return $result;
    }


}
